<%@ page language="java" import="com.alibaba.fastjson.JSONArray" pageEncoding="UTF-8" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="okhttp3.*" %>
<%@ page import="org.apache.axis.encoding.Base64" %>
<%@ page import="weaver.common.DateUtil" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.formmode.setup.ModeRightInfo" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.TimeUtil" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="weaver.interfaces.zhlx.duss.utils.PropUtil" %>
<%@ page import="java.math.BigDecimal" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.Set" %>
<%@ page import="java.util.UUID" %>
<%@ page import="java.util.concurrent.TimeUnit" %>
<%--建模同步数据调用SAP未清应收应付接口--%>
<%
    BaseBean baseBean = new BaseBean();
    String rq = Util.null2String(request.getParameter("rq"));
    String lzdjh = Util.null2String(request.getParameter("lzdjh"));
    Map<String, Object> apidatas = new HashMap<String, Object>();
    String code = "SUCCESS";
    JSONObject data = new JSONObject();
    String message = "";
    try {
        baseBean.writeLog(">>>>>getWqysyfBySAP>>>>>rq=" + rq + "<br/>");
        if (!"".equals(rq)) {
            int formmodeid = getFormmodeid("uf_sapwqyfwqyssj");
            String currentDate = DateUtil.getCurrentDate();
            JSONObject dataJson = new JSONObject();
            dataJson.put("BUKRS", "");
            dataJson.put("GJAHR", "");
            dataJson.put("MONAT", "");
            dataJson.put("BELNR", lzdjh);
            dataJson.put("BUDAT", rq.replace("-", ""));
            dataJson.put("ZLAIYUAN", "");
            JSONObject resultJson = handleOKHttpRequest("FI007", dataJson);
            String status = Util.null2String(resultJson.getString("code"));
            baseBean.writeLog(">>>>>getWqysyfBySAP>>>>>status=" + status + "<br/>");
            if ("success".equals(status)) {
                String output = Util.null2String(resultJson.getString("OUTPUT"));
                JSONObject outputJson = JSONObject.parseObject(output);
                String msgType = outputJson.getString("MSG_TYPE");
                String msgText = outputJson.getString("MSG_TEXT");
                baseBean.writeLog(">>>>>getWqysyfBySAP>>>>>msgType=" + msgType + "<br/>");
                baseBean.writeLog(">>>>>getWqysyfBySAP>>>>>msgText=" + msgText + "<br/>");
                if ("S".equals(msgType) && "调用成功".equals(msgText)) {
                    String dataReturnStr = outputJson.getString("DATA");
                    JSONObject dataReturnJson = JSONObject.parseObject(dataReturnStr);
                    String returnData = dataReturnJson.getString("RETURN");
                    baseBean.writeLog(">>>>>getWqysyfBySAP>>>>>returnData=" + returnData + "<br/>");
                    JSONArray returnList = JSONArray.parseArray(returnData);
                    int count = 0;
                    int counts = returnList.size();
                    for (int i = 0; i < returnList.size(); i++) {
                        JSONObject paramJson = new JSONObject();
                        paramJson.put("rq", currentDate);
                        String gsdm = returnList.getJSONObject(i).getString("BUKRS");
                        paramJson.put("gsdm", gsdm);
                        paramJson.put("gsmc", getGsmcByGsdm(gsdm));
                        String lzdjh1 = returnList.getJSONObject(i).getString("BELNR");
                        paramJson.put("lzdjh", lzdjh1);
                        String bz = returnList.getJSONObject(i).getString("WAERS");
                        paramJson.put("bz", bz);
                        String ywqrr = returnList.getJSONObject(i).getString("PPNAM");
                        paramJson.put("ywqrr", ywqrr);
                        String tbbm = getUserInfo(ywqrr).get("departmentid");
                        String ywqrrid = getUserInfo(ywqrr).get("id");
                        String lrzxbm = returnList.getJSONObject(i).getString("PRCTR");
                        paramJson.put("lrzxbm", lrzxbm);
                        if (!"".equals(ywqrrid)) {
                            paramJson.put("tbbm", tbbm);
                            paramJson.put("ywqrrrl", ywqrrid);
                        }
                        if (!"".equals(lrzxbm)) {
                            tbbm = getLrzxbmdz(lrzxbm);
                            paramJson.put("tbbm", tbbm);
                        }
                        String cjr = returnList.getJSONObject(i).getString("USNAM");
                        paramJson.put("cjr", cjr);
                        String cjrbm = getUserInfo(cjr).get("departmentid");
                        String cjrrl = getUserInfo(cjr).get("id");
                        if (!"".equals(cjrrl)) {
                            paramJson.put("cjrbm", cjrbm);
                            paramJson.put("cjrrl", cjrrl);
                        }
                        String ksbm = returnList.getJSONObject(i).getString("KESHANG");
                        paramJson.put("ksbm", ksbm);
                        paramJson.put("wlkmbm", returnList.getJSONObject(i).getString("HKONT"));
                        paramJson.put("wlkmbs", returnList.getJSONObject(i).getString("TXT20"));
                        String ydzqysfyeyb = returnList.getJSONObject(i).getString("WRBTR");
                        paramJson.put("ydzqysfyeyb", ydzqysfyeyb);
                        paramJson.put("zsbbje", getbbje(bz, ydzqysfyeyb));
                        paramJson.put("jyzfnr", returnList.getJSONObject(i).getString("SGTXT"));
                        paramJson.put("dqrq", returnList.getJSONObject(i).getString("NETDT"));
                        String zffs = returnList.getJSONObject(i).getString("ZLSCH");
                        paramJson.put("zffs", zffs);
                        if (!"".equals(zffs)) {
                            int zffs1 = 0;
                            if (!"T".equalsIgnoreCase(zffs)) {
                                zffs1 = 1;
                            }
                            paramJson.put("zffs1", zffs1);
                        }
                        String zlaiyuan = returnList.getJSONObject(i).getString("ZLAIYUAN");
                        int ly = 1;
                        if ("K".equalsIgnoreCase(zlaiyuan)) {
                            ly = 0;
                            if (!"".equalsIgnoreCase(zffs)) {
                                Map<String, String> map = getGysxxByKsbm(ksbm, "电汇");
                                String yxzhdm = Util.null2String(map.get("yxzhdm"));
                                String yxzh = Util.null2String(map.get("yxzh"));
                                String khyx = Util.null2String(map.get("khyx"));
                                paramJson.put("lhhdh", yxzhdm);
                                paramJson.put("yxzhdh", yxzh);
                                paramJson.put("khyhdh", khyx);
                            }
                            if (!"".equalsIgnoreCase(zffs)) {
                                Map<String, String> map = getGysxxByKsbm(ksbm, "承兑");
                                String yxzhdm = Util.null2String(map.get("yxzhdm"));
                                String yxzh = Util.null2String(map.get("yxzh"));
                                String khyx = Util.null2String(map.get("khyx"));
                                paramJson.put("lhhcd", yxzhdm);
                                paramJson.put("yxzhcd", yxzh);
                                paramJson.put("khyhcd", khyx);
                            }
                        }

                        String ksmc = ly == 1 ? getKhzsjByKsbm(ksbm) : getGyszsjByKsbm(ksbm);
                        paramJson.put("ksmc", ksmc);
                        String jzm = returnList.getJSONObject(i).getString("BSCHL");
                        //供应商未清：记账码21-28，资金计划计入SAP应收
                        //客户未清：记账码11-18，资金计划计入SAP应付
                        if (11 <= Util.getIntValue(jzm, -1) && Util.getIntValue(jzm, -1) <= 18) {
                            ly = 0;
                        }
                        if (21 <= Util.getIntValue(jzm, -1) && Util.getIntValue(jzm, -1) <= 28) {
                            ly = 1;
                        }
                        paramJson.put("ly", ly);
                        String hjnd = returnList.getJSONObject(i).getString("GJAHR");
                        paramJson.put("hjnd", hjnd);
                        String yfpzxxmh = returnList.getJSONObject(i).getString("BUZEI");
                        paramJson.put("yfpzxxmh",yfpzxxmh );
                        paramJson.put("jzm", jzm);
                        String wym  =hjnd+gsdm+lzdjh1+yfpzxxmh;
                        paramJson.put("wym", wym);
                        String jsfph = returnList.getJSONObject(i).getString("ZJINSHUIHAOMA");
                        paramJson.put("jsfph",jsfph);
                        String inputdate = returnList.getJSONObject(i).getString("ZZJINSHUIRIQI");
                        paramJson.put("kprq",inputdate);

                        int dataid = insertModelData(formmodeid, paramJson);
                        if (dataid > 0) {
                            count++;
                        }
                    }
                    if (count == counts) {
                        data.put("count", count);
                        data.put("counts", counts);
                    }
                }
            } else {
                code = "FAIL_ERROR";
                message = "接口响应异常";
            }
        } else {
            code = "PARAMTER_ERROR";
            message = "接口参数异常";
        }
    } catch (Exception e) {
        e.printStackTrace();
        code = "SYSTEM_INNER_ERROR";
        message = "程序内部异常";
    }
    apidatas.put("code", code);
    apidatas.put("data", data);
    apidatas.put("message", message);
    out.print(JSONObject.toJSONString(apidatas));
%>
<%!

    private static final JSONObject propVal = PropUtil.getPropVal("zhlxsap");
    private static final String URL = propVal.getString("url")+"/RESTAdapter/ec/interface";
    private static final String USERNAME = propVal.getString("username");
    private static final String PASSWORD = propVal.getString("password");

    private static JSONObject handleOKHttpRequest(String type, JSONObject dataJson) {
        JSONObject paramsJson = new JSONObject();
        JSONObject inuptJson = new JSONObject();
        String fullDate = DateUtil.getFullDate();
        String curdate = fullDate.substring(0, 10).replace("-", "");
        String curtime = fullDate.substring(11, 19).replace(":", "");
        JSONObject headerJson = new JSONObject();
        headerJson.put("SYSID", "EC");
        headerJson.put("BUSINESS", type);
        headerJson.put("BUSNKEY", "");
        headerJson.put("TECHKEY", getUUIDStr());
        headerJson.put("DATE", curdate);
        headerJson.put("TIME", curtime);
        inuptJson.put("HEADER", headerJson);
        inuptJson.put("DATA", dataJson);
        paramsJson.put("INPUT", inuptJson.toJSONString());
        return sendOKHttpRequest(paramsJson);
    }

    private static JSONObject sendOKHttpRequest(JSONObject params) {
        JSONObject resultJson = new JSONObject();
        String code = "fail";
        String message = "";
        try {
            String authorization = " Basic " + Base64.encode((USERNAME + ":" + PASSWORD).getBytes());
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params.toJSONString());
            Request request = new Request.Builder()
                    .url(URL)
                    .method("POST", body)
                    .addHeader("Authorization", authorization)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            if (!"".equals(result)) {
                resultJson = JSONObject.parseObject(result);
                code = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("code", code);
        resultJson.put("message", message);
        return resultJson;
    }

    //建模权限重构
    private void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    //将数据插入表单建模
    private int insertModelData(int modeid, JSONObject paramJson) {
        BaseBean baseBean = new BaseBean();
        int dataid = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        String sql = "select b.tablename,a.formid from modeinfo a left join workflow_bill b on a.formid=b.id where a.id=?";
        rs.executeQuery(sql, modeid);
        rs.next();
        String tablename = Util.null2String(rs.getString("tablename"));
        String uuid = UUID.randomUUID().toString();
        String insSql = "insert into " + tablename
                + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
        Object[] params = {uuid, 1, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
        if (rs.executeUpdate(insSql, params)) {
            rs1.executeQuery("select id from " + tablename + " where modeuuid=?", uuid);
            rs1.next();
            dataid = Util.getIntValue(rs1.getString("id"));
            if (dataid > 0) {
                Map<String, Object> map = JSONObject.toJavaObject(paramJson, Map.class);
                //遍历数据 进行update
                String updatesql = "update " + tablename + " set ";
                Set<String> keySet = map.keySet();
                for (String key : keySet) {
                    updatesql += key + "='" + Util.null2String(map.get(key)) + "',";
                }
                if (updatesql.endsWith(",")) {
                    updatesql = updatesql.substring(0, updatesql.length() - 1);
                    updatesql += " where id=" + dataid;
                    baseBean.writeLog(">>>>>insertModelData>>>>>updatesql=" + updatesql);
                    boolean updateFlag = rs.executeUpdate(updatesql);
                    if (!updateFlag) {
                        dataid = -1;
                    }
                }
                //进行权限重构
                newModeRight(1, modeid, dataid);
            }
        }
        return dataid;
    }

    private int getFormmodeid(String tablename) {
        RecordSet rs = new RecordSet();
        String sql = "select m.id from modeinfo m left join WORKFLOW_BILL b on m.formid = b.id where b.tablename = ?";
        rs.executeQuery(sql, tablename);
        rs.next();
        return Util.getIntValue(rs.getString("id"));
    }

    private static String getUUIDStr() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replace("-", "");
    }

    /**
     *@Description: 获取人员信息
     *@Param: workcode
     *@return: java.lang.String
     *@Author: Dusongsong
     *@Date: 2022/9/6
     */
    private static Map<String, String> getUserInfo(String workcode) {
        RecordSet rs = new RecordSet();
        Map<String, String> map = new HashMap<>();
        rs.executeQuery("select id,departmentid from hrmresource where workcode=?", workcode);
        rs.next();
        map.put("id", Util.null2String(rs.getString("id")));
        map.put("departmentid", Util.null2String(rs.getString("departmentid")));
        return map;
    }

    /**
     * 根据公司代码获取公司名称
     * @param gsdm
     * @return
     */
    private static String getGsmcByGsdm(String gsdm) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select gsmc from uf_gsxx where gsdm=?", gsdm);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 根据供应商编码获取供应商主数据信息
     * @param gysbm
     * @return
     */
    private static Map<String, String> getGysxxByKsbm(String gysbm, String kzm) {
        RecordSet rs = new RecordSet();
        Map<String, String> map = new HashMap<>();
        rs.executeQuery("select id from uf_sapgyszsj where gysbm=?", gysbm);
        rs.next();
        String mainid = Util.null2String(rs.getString("id"));
        rs.executeQuery("select yxzhdm,yxzh,khyx,ckxj from uf_sapgyszsj_dt1 where mainid=? and kzm=? order by yxqksrq,yxqjsrq desc", mainid, kzm);
        rs.next();
        map.put("yxzhdm", Util.null2String(rs.getString("yxzhdm")));
        String ckxj = Util.null2String(rs.getString("ckxj"));
        String yxzh = Util.null2String(rs.getString("yxzh"));
        map.put("yxzh", yxzh+ckxj);
        map.put("khyx", Util.null2String(rs.getString("khyx")));
        return map;
    }

    /**
     * 根据客商编码获取客户主数据信息
     * @param ksbm
     * @return
     */
    private static String getKhzsjByKsbm(String ksbm) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select khmcq from uf_sapkhzsj where trim(khbh)=? order by khmcq", ksbm);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 根据客商编码获取供应商主数据信息
     * @param ksbm
     * @return
     */
    private static String getGyszsjByKsbm(String ksbm) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select gysqc from uf_sapgyszsj where trim(gysbm)=? order by gysqc", ksbm);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 获取本币金额
     * @return
     */
    private static String getbbje(String wbbb, String wbje) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select (hl/wbsl) from uf_saphlb where wbbb=? and bbbb='CNY' order by sxrq desc", wbbb);
        rs.next();
        String hl = Util.null2String(rs.getString(1));
        return fMultiply(hl, wbje, 2);
    }


    // 乘法保留小数位
    public static String fMultiply(String a, String b, int n) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);
        BigDecimal bd = bg1.multiply(bg2).setScale(n, BigDecimal.ROUND_HALF_UP);
        return bd.toString();
    }

    public static String isZero(String a) {
        if ("".equals(a)) {
            a = "0";
        }
        return a;
    }

    //利润中心与EC部门对照
    public static String getLrzxbmdz(String lrzxbm) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select ecbm from uf_lrzxbmdz where lrzxbm=?", lrzxbm);
        rs.next();
        return Util.null2String(rs.getString(1));
    }
%>



